package com.lsh.oms.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.oms.core.model.calService.CalResultVo;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * @author peter
 */
public class BillsResultUtil {

    static Logger logger = LoggerFactory.getLogger(BillsResultUtil.class);

    private static String cal_url = "/cal/index/shipping";

    public static ResultVo doBiz(ParamsVo paramsVo, String url, String logSign, Long venderId) {

        ResultVo resultVo = new ResultVo();

        if (paramsVo.getClass().equals(DeleveryParams.class)) {
            DeleveryParams deleveryParams = (DeleveryParams) paramsVo;
            List<BasicNameValuePair> pairs = new ArrayList<>(2);
            pairs.add(new BasicNameValuePair("item_list", JsonUtils.obj2Json(deleveryParams.getItemList())));
            pairs.add(new BasicNameValuePair("order_id", deleveryParams.getOrder_id()));

            HttpEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
            String urlShipping = url + cal_url;
            logger.info(logSign + ":请求发货服务URL: " + urlShipping);
            // 请求头
            Header[] headers = {new BasicHeader("api-version", "1.1"),
                    new BasicHeader("platform", "oms"),
                    new BasicHeader("venderId", venderId + ""),
                    new BasicHeader("sign", "mk5")};

            String res;
            try {
                long start = System.currentTimeMillis();
                res = HttpUtils.post(urlShipping, entity, false, headers).getData();
                logger.info(logSign + ":发货服务耗时是: " + (System.currentTimeMillis() - start) + "ms");
                logger.info(logSign + ":发货服务返回结果是: " + res);

                if (StringUtils.isNotBlank(res)) {
                    JSONObject calJson = JSON.parseObject(res);
                    resultVo.setRet(calJson.getIntValue("ret"));
                    resultVo.setTimestamp(calJson.getIntValue("timestamp"));
                    resultVo.setMsg(calJson.getString("msg"));

                    CalResultVo calResultVo = JSON.parseObject(calJson.getString("content"), CalResultVo.class);
                    resultVo.setData(calResultVo);
                    return resultVo;
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(logSign + " : 发货服务返回结果转json失败");
                return null;
            }
        }

        logger.info(logSign + " :请求发货计算服务参数传递异常!");
        return null;
    }
}
